<script src="js/3rd/jquery-1.6.2.min.js" ></script>
<script src="js/3rd/jquery-ui-1.8.16.custom.min.js" ></script>

<script>

$.ready = function()
{
	$('body').disableSelection();

	$( "#Hand").sortable();
	
	$( ".Item" ).draggable({ helper: 'clone' });
	
	$("#Deck").droppable(
	{
			accept: ".Item",
			drop: $.deck_drop
	});
	
	$("Body").droppable(
	{
			accept: ".Item",
			drop: function(event, ui) {
				var item = $(ui.draggable);
				if(item[0].parentElement == $("#Deck")[0])
				{
						item.remove();					
				}
			}
	});
	
}

$.item_drop = function(event, ui)
{
	
	var a = $(ui.draggable).html();
	var b = $(this).html();

	if(b % a == 0 || a % b == 0)
	{
		var item = $(ui.draggable);
		
		if(item[0].parentElement == $("#Deck")[0])
			$(ui.draggable).remove();
			
		$(this).remove();
		
		var val  = parseInt(b) + parseInt(a);
		var id = "i" + val;
		
		if($("#" + id)[0] == null)
		{
			var s = '<div class="Item" id="'+id+'">' + val + '</div>';
			
			$("#Hand").append(s);
			
			$("#" + id).draggable({ helper: 'clone' });
		}
		
		clone = $("#" + id).clone();
		
		clone.attr('id', '');

		clone.draggable();
		
		clone.css("position", "absolute");
		clone.css("top", ui.position.top);
		clone.css("left", ui.position.left);
		
		$("#Deck").append(clone);
		
		clone.droppable(
		{
			greedy:true,
			drop: $.item_drop,
		}
		);

		
	//	$("#" + id).clone().append("#Deck");
		
		
	}
	else
	{
//alert(1);
		//$(ui.draggable).draggable({ revert: 'invalid' });
		
		$( ui.draggable ).draggable({ revert: true });
	}
		
	
};

$.deck_drop = function(event, ui)
{
$( ui.draggable ).draggable({ revert: false });
	var item = $(ui.draggable);
	if(item[0].parentElement == $("#Hand")[0])
	{
		var clone = item.clone();
		
		clone.draggable();
		
		clone.css("position", "absolute");
		clone.css("top", ui.position.top);
		clone.css("left", ui.position.left);
		clone.attr('id', '');
		
		clone.droppable(
		{
			greedy:true,
			drop: $.item_drop
		}
		);
		
		$("#Deck").append(clone);	
	}
};

</script>


<style>
.Item {
  height: 60px;
  width: 50px;
  float: left;
  border: 2px solid #999;
  background-color: #CCF;
  margin: 2px;
  border-radius: 10px;
  text-align: center;
  color:#666;
  font-family:calibri;
 }

#Deck
{
	width:82%;
	height:80%;
	background-color: #DDD;
	border-radius: 10px;
	padding:10px;
	float: right;
}

#Hand
{
	background-color: #eee;
	border-radius: 10px;
	padding:10px;	
	height:80%;
}

</style>

<div id="Deck">
</div>


<div id="Hand">
  <div class="Item" id="i1">1</div>
  <div class="Item" id="i2">2</div>
  <div class="Item" id="i3">3</div>
</div>




